package com.micro.ai.agents.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.ai.commons.exception.BusinessException;
import com.micro.ai.agents.entity.Message;
import com.micro.ai.agents.mapper.MessageMapper;
import com.micro.ai.agents.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message create(Message message) {
        if (message == null) {
            throw new BusinessException("A0000", "消息信息不能为空");
        }
        
        if (!StringUtils.hasText(message.getConversationId())) {
            throw new BusinessException("A0000", "会话ID不能为空");
        }
        
        if (!StringUtils.hasText(message.getRole())) {
            throw new BusinessException("A0000", "消息角色不能为空");
        }
        
        if (!StringUtils.hasText(message.getContent())) {
            throw new BusinessException("A0000", "消息内容不能为空");
        }
        
        if (message.getMessageOrder() == null) {
            // 自动计算下一个顺序号
            LambdaQueryWrapper<Message> query = new LambdaQueryWrapper<>();
            query.eq(Message::getConversationId, message.getConversationId())
                 .orderByDesc(Message::getMessageOrder)
                 .last("LIMIT 1");
            
            Message lastMessage = this.getOne(query);
            int nextOrder = lastMessage != null ? lastMessage.getMessageOrder() + 1 : 1;
            message.setMessageOrder(nextOrder);
        }
        
        if (message.getMessageType() == null) {
            message.setMessageType("text");
        }
        if (message.getTokensUsed() == null) {
            message.setTokensUsed(0);
        }
        if (message.getInputTokens() == null) {
            message.setInputTokens(0);
        }
        if (message.getOutputTokens() == null) {
            message.setOutputTokens(0);
        }
        if (message.getCost() == null) {
            message.setCost(java.math.BigDecimal.ZERO);
        }
        
        message.setCreatedAt(LocalDateTime.now());
        
        boolean success = this.save(message);
        if (!success) {
            throw new BusinessException("A0003", "保存消息失败");
        }
        
        log.debug("创建消息成功: messageId={}, conversationId={}, role={}, order={}", 
                message.getId(), message.getConversationId(), message.getRole(), message.getMessageOrder());
        return message;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchCreate(List<Message> messages) {
        if (messages == null || messages.isEmpty()) {
            throw new BusinessException("A0000", "消息列表不能为空");
        }
        
        LocalDateTime now = LocalDateTime.now();
        for (Message message : messages) {
            if (message.getMessageOrder() == null) {
                throw new BusinessException("A0000", "批量创建时消息顺序必须指定");
            }
            if (message.getCreatedAt() == null) {
                message.setCreatedAt(now);
            }
        }
        
        return this.saveBatch(messages);
    }

    @Override
    public List<Message> listByConversationId(String conversationId) {
        LambdaQueryWrapper<Message> query = new LambdaQueryWrapper<>();
        query.eq(Message::getConversationId, conversationId)
             .orderByAsc(Message::getMessageOrder);
        
        return this.list(query);
    }

    @Override
    public Page<Message> pageQuery(int pageNum, int pageSize, String tenantId, String conversationId, String role) {
        if (pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize < 1 || pageSize > 100) {
            pageSize = 20;
        }
        
        Page<Message> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Message> query = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(tenantId)) {
            query.eq(Message::getTenantId, tenantId);
        }
        if (StringUtils.hasText(conversationId)) {
            query.eq(Message::getConversationId, conversationId);
        }
        if (StringUtils.hasText(role)) {
            query.eq(Message::getRole, role);
        }
        
        query.orderByAsc(Message::getMessageOrder)
             .orderByAsc(Message::getCreatedAt);
        
        return this.page(page, query);
    }
}

